import { watch } from 'vue';
import { useAppStore } from '/@/store/modules/app';

export function useByteluckTheme() {
  const appStore = useAppStore();
  const defaultTheme: any = {
    token: {
      wireframe: true,
      colorPrimary: '#06be87',
      colorPrimaryHover: '#29c798',
      colorPrimaryActive: '#06b17e',
      colorPrimaryBorder: '#dee0e3',
      colorPrimaryBorderHover: '#29c798',
      colorBgTextActive: 'rgba(6,190,135,.1)',
      colorLink: '#06be87',
      colorLinkHover: '#29c798',
      colorLinkActive: '#06b17e',
      boxShadowTertiary: '',
      borderRadius: 4,
      colorBorder: '#dee0e3',
      controlHeight: 30,
    },
    components: {
      Cascader: {
        colorBgContainerDisabled: '#f2f3f5',
      },
      Input: {
        colorTextDisabled: 'rgba(0, 0, 0, 0.88)',
        colorBgContainerDisabled: '#f2f3f5',
      },
      DatePicker: {
        colorTextDisabled: 'rgba(0, 0, 0, 0.88)',
        colorBgContainerDisabled: '#f2f3f5',
      },
      Mentions: {
        colorTextDisabled: 'rgba(0, 0, 0, 0.88)',
        colorBgContainerDisabled: '#f2f3f5',
      },
      Select: {
        colorTextDisabled: 'rgba(0, 0, 0, 0.88)',
        colorBgContainerDisabled: '#f2f3f5',
      },
      Modal: {
        fontWeightStrong: 400,
      },
      Table: {
        fontWeightStrong: 400,
      },
      Button: {
        controlHeight: 'var(--layout-button-height,28px)',
        paddingContentHorizontal: 8,
      },
    },
  };

  const cssVariable = {
    '--bl-brand-c': '',
    '--bl-brand-hover': '',
    '--bl-brand-active': '',
    '--bl-brand-disable': '',
    '--bl-brand-label': '',
  };

  // 解析颜色字符串为RGB值
  function parseColor(color: string) {
    const hex = color.replace(/^#/, '');
    const r = parseInt(hex.slice(0, 2), 16);
    const g = parseInt(hex.slice(2, 4), 16);
    const b = parseInt(hex.slice(4, 6), 16);
    return { r, g, b };
  }

  // 将RGB值转换为十六进制颜色字符串
  function componentToHex(c: number) {
    const hex = c.toString(16);
    return hex.length === 1 ? '0' + hex : hex;
  }

  /**
   * 两种颜色混合后的值
   * @param {string} color1 颜色1
   * @param {string} color2 颜色2
   * @param {number} weight 权重
   * @return {string} blendedColor 最终结果
   */
  function blendColors(color1: string, color2: string, weight: number) {
    const color1RGB = parseColor(color1);
    const color2RGB = parseColor(color2);

    // 计算混合后的RGB值
    const blendedR = Math.round((1 - weight) * color1RGB.r + weight * color2RGB.r);
    const blendedG = Math.round((1 - weight) * color1RGB.g + weight * color2RGB.g);
    const blendedB = Math.round((1 - weight) * color1RGB.b + weight * color2RGB.b);

    return `#${componentToHex(blendedR)}${componentToHex(blendedG)}${componentToHex(blendedB)}`;
  }
  // 将十六进制颜色转换为RGB，然后转换为RGBA
  const hexToRgba = (hex: string, alpha: number) => {
    const r = parseInt(hex.slice(1, 3), 16);
    const g = parseInt(hex.slice(3, 5), 16);
    const b = parseInt(hex.slice(5, 7), 16);
    return `rgba(${r}, ${g}, ${b}, ${alpha})`;
  };
  /**
   * 根据主题色计算 hover 色值
   * @param {string} themeColor 主题色，十六进制字符串
   * @return {Object} 包含 hover 色值的对象
   */
  function calculateColors(themeColor: string) {
    const hoverWeight = 0.2; // hover 颜色混合权重
    const disabledWeight = 0.5; // disabled 颜色混合权重
    const activeWeight = 0.1;
    const labelWeight = 0.1;
    const white = '#ffffff';
    const black = '#000000';
    return {
      hover: blendColors(themeColor, white, hoverWeight),
      disabled: blendColors(themeColor, white, disabledWeight),
      active: blendColors(themeColor, black, activeWeight),
      label: hexToRgba(themeColor, labelWeight),
    };
  }

  function resetByteluckTheme(colorPrimary: string) {
    const colors = calculateColors(colorPrimary);

    cssVariable['--bl-brand-c'] = colorPrimary;
    cssVariable['--bl-brand-hover'] = colors.hover;
    cssVariable['--bl-brand-active'] = colors.active;
    cssVariable['--bl-brand-disable'] = colors.disabled;
    cssVariable['--bl-brand-label'] = colors.label;

    defaultTheme.token.colorPrimary = colorPrimary;
    defaultTheme.token.colorPrimaryHover = colors.hover;
    defaultTheme.token.colorPrimaryActive = colors.active;
    defaultTheme.token.colorPrimaryBorder = colors.disabled;
    defaultTheme.token.colorLink = colorPrimary;
    defaultTheme.token.colorLinkHover = colors.hover;
    defaultTheme.token.colorLinkActive = colors.active;

    document.body.style.setProperty('--bl-brand-c', colorPrimary);
    document.body.style.setProperty('--bl-brand-hover', colors.hover);
    document.body.style.setProperty('--bl-brand-active', colors.active);
    document.body.style.setProperty('--bl-brand-disable', colors.disabled);
    document.body.style.setProperty('--bl-brand-label', colors.label);
  }

  function initListenThemePostmessage() {
    window.addEventListener('message', (event) => {
      if (event.data.type === 'PARENT_CUSTOM_THEME') {
        // 当前iframe
        const currentIframe = event.source;
        // 向当前iframe发送回复
        if (currentIframe) {
          currentIframe.postMessage(
            {
              type: 'PARENT_CUSTOM_THEME',
              data: {
                antd: defaultTheme,
                css: cssVariable,
              },
            },
            '*'
          );
        }
      }
    });
  }

  watch(
    appStore.getProjectConfig,
    (newValue) => {
      const primary = newValue.themeColor;
      resetByteluckTheme(primary);
      const iframeList = document.querySelectorAll('iframe');
      iframeList.forEach((iframe) => {
        iframe.contentWindow.postMessage(
          {
            type: 'PARENT_CUSTOM_THEME',
            data: {
              antd: defaultTheme,
              css: cssVariable,
            },
          },
          '*'
        );
      });
    },
    {
      deep: true,
    }
  );

  return {
    resetByteluckTheme,
    initListenThemePostmessage,
  };
}
